class ProgressView {
  constructor(dom, option) {
    this.option = option;
    this.dom = dom;
  }

  render() {
    this.initCanvas();
    this.initData();
    this.timer = setInterval(() => {
      if (this.score < this.data.score) {
        this.score += 1;
        this.repaint();
      } else {
        clearInterval(this.timer);
        this.timer = null;
      }
    }, 10)
  }

  repaint() {
    this.ctx.beginPath();
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.ctx.fillStyle = this.backColor;
    this.ctx.moveTo(this.sx, this.sy);
    this.ctx.lineTo(this.ex, this.sy);
    this.ctx.arc(this.ex, (this.sy + this.ey) / 2, this.radius, 3 * Math.PI / 2, 5 * Math.PI / 2);
    this.ctx.lineTo(this.sx, this.ey);
    this.ctx.arc(this.sx, (this.sy + this.ey) / 2, this.radius, Math.PI / 2, 3 * Math.PI / 2);
    this.ctx.fill();
    if (this.data.score > 80) {
      this.ctx.fillStyle = this.colorList[0];
    } else if (this.data.score > 30) {
      this.ctx.fillStyle = this.colorList[1];
    } else {
      this.ctx.fillStyle = this.colorList[2];
    }
    let tx = this.sx + (this.ex - this.sx) * this.score / 100;
    this.ctx.beginPath();
    this.ctx.moveTo(this.sx, this.sy);
    this.ctx.lineTo(tx, this.sy);
    this.ctx.arc(tx, (this.sy + this.ey) / 2, this.radius, 3 * Math.PI / 2, 5 * Math.PI / 2);
    this.ctx.lineTo(this.sx, this.ey);
    this.ctx.arc(this.sx, (this.sy + this.ey) / 2, this.radius, Math.PI / 2, 3 * Math.PI / 2);
    this.ctx.fill();
    this.drawLabel(this.fontSize);
  }

  initCanvas(){
    this.canvas = document.createElement('canvas');
    const style = window.getComputedStyle(this.dom,'null');
    this.canvas.setAttribute('width',style.width);
    this.canvas.setAttribute('height', style.height);
    this.canvas.style.margin = '0';
    this.canvas.style.padding = '0';
    this.dom.appendChild(this.canvas);
    this.ctx = this.canvas.getContext("2d");
  }

  initData() {
    this.data = this.option.series[0];
    this.height = 18;
    this.sx = 12;
    this.sy = 0;
    this.ex = this.canvas.width -12;
    this.ey = this.sy + this.height;
    this.radius = (this.ey - this.sy) / 2;
    this.backColor = '#ebeef5';
    this.colorList = ['#67c23a', '#e6a23c', '#f56c6c'];
    this.score = 0;
    this.fontSize = 14;
  }

  drawLabel(fontSize) {
    this.ctx.beginPath();
    this.ctx.fillStyle = 'white';
    this.ctx.textAlign = 'center';
    this.ctx.font = `${fontSize}px Arial`;
    this.ctx.fillText(this.data.score + '%', (this.sx + this.ex) / 2, this.sy + (this.ey - this.sy) * 0.8);
  }

}
